package com.tanxiaoyao.wecon.ui;


import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import android.widget.LinearLayout.LayoutParams;

import com.tanxiaoyao.wecon.R;
import com.tanxiaoyao.wecon.app.AppManager;
import com.tanxiaoyao.wecon.common.UIHelper;
import com.tanxiaoyao.wecon.widget.PopMenu;

/**
 * 主界面类：展示tab栏
 *
 * @author tanxiaoyao (junlidev@gmail.com)
 * @version 2014-8-27 下午8:55:49
 */
public class ActivityMain extends TabActivity implements View.OnClickListener {
	
	// DEBUG标志
		private static final String TAG = "tanxiaoyao-tabactivity";
		private static final Boolean ISDEBUG = false;

    public static final String TAB_TAG_HOME = "home";
    public static final String TAB_TAG_MOUSE = "mouse";
    public static final String TAB_TAG_PPT = "powerpoint";
    public static final String TAB_TAG_SIMULATE = "simulate";
    public static TabHost mTabHost;
    public TextView mHomeTv, mMouseTv, mPowerPointTv, mSimulateTv, mMenuTv;
    //当前选中tab页id,初始默认为首页界面
    int mCurTabId = R.id.tab_home;
    //界面动画
    private Animation anim_left_in, anim_left_out, anim_right_in, anim_right_out;
    private Intent mHomeIntent, mMouseIntent, mPhoneIntent, mCompIntent;
    //    弹出菜单
    private PopMenu popMenu;

    //    菜单图片和文字资源
    private int[] resArray = new int[]{
            R.drawable.icon_sensors,
            R.drawable.icon_about,
            R.drawable.icon_quit
    };

    private String[] title = new String[]{
            "传感器", "关于", "退出"
    };
    private GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        if(ISDEBUG) Log.i("xiaoyao", "Main onCreate");
//      去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        设置界面View
        setContentView(R.layout.main_footer);
//        初始化界面左右切换动画
        initAnim();
//        初始化界面切换Intent
        initIntent();
//        为每个Tab页绑定Intent
        bindIntent();
//        初始化每个页面
        initView();
    }


    /**
     * 初始化页面方法
     */
    private void initView() {
//       得到控件
        mHomeTv = (TextView) findViewById(R.id.tv_home);
        mMouseTv = (TextView) findViewById(R.id.tv_mouse);
        mPowerPointTv = (TextView) findViewById(R.id.tv_phone);
        mSimulateTv = (TextView) findViewById(R.id.tv_comp);
        mMenuTv = (TextView) findViewById(R.id.tv_menu);
//        得到可点击的view，设置监听器
        findViewById(R.id.tab_home).setOnClickListener(this);
        findViewById(R.id.tab_mouse).setOnClickListener(this);
        findViewById(R.id.tab_phone).setOnClickListener(this);
        findViewById(R.id.tab_comp).setOnClickListener(this);
        findViewById(R.id.tab_menu).setOnClickListener(this);

    }

    /**
     * 生成tabSpec方法
     *
     * @param tag      tab页面标识
     * @param resLabel tab显示名称
     * @param resIcon  tab图标
     * @param content  tab页转换对应Intent
     * @return TabSpec对象
     */
    private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon,
                                         final Intent content) {
        return mTabHost
                .newTabSpec(tag)
                .setIndicator(getString(resLabel),
                        getResources().getDrawable(resIcon))
                .setContent(content);
    }

    /**
     * 设置Tab页
     */
    private void bindIntent() {
//        得到tabhost
        mTabHost = getTabHost();
//        分别添加上tab
        mTabHost.addTab(buildTabSpec(TAB_TAG_HOME, R.string.home,
                R.drawable.icon_home_nc, mHomeIntent));
        mTabHost.addTab(buildTabSpec(TAB_TAG_MOUSE, R.string.mouse,
                R.drawable.icon_mouse_nc, mMouseIntent));
        mTabHost.addTab(buildTabSpec(TAB_TAG_PPT, R.string.powerpoint,
                R.drawable.icon_phone_nc, mPhoneIntent));
        mTabHost.addTab(buildTabSpec(TAB_TAG_SIMULATE, R.string.simulate,
                R.drawable.icon_comp_nc, mCompIntent));
    }

    /**
     * 切面切换Intent初始化
     */
    private void initIntent() {
        mHomeIntent = new Intent(this, ActivityHome.class);
        mMouseIntent = new Intent(this, ActivityMouse.class);
        mPhoneIntent = new Intent(this, ActivityPowerPoint.class);
        mCompIntent = new Intent(this, ActivitySimulate.class);
    }

    /**
     * 初始化tab页面左右界面切换动画
     */
    private void initAnim() {
        anim_left_in = AnimationUtils.loadAnimation(this, R.anim.left_in);
        anim_left_out = AnimationUtils.loadAnimation(this, R.anim.left_out);
        anim_right_in = AnimationUtils.loadAnimation(this, R.anim.right_in);
        anim_right_out = AnimationUtils.loadAnimation(this, R.anim.right_out);
    }


    /**
     * tab子view点击事件处理方法
     *
     * @param view 被点击的View
     */
    @Override
    public void onClick(View view) {
        if (mCurTabId == view.getId() && view.getId() != R.id.tab_menu) {
//            重复点击当前所在tab不予反应,设置除外
            return;
        }
//        首先判断是否弹出菜单窗口
        if (view.getId() == R.id.tab_menu) {
            popupMenu();
            return;
        }
//        首先将所有页面设置为未选中状态
        mHomeTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_home_nc, 0, 0);
        mMouseTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_mouse_nc, 0, 0);
        mPowerPointTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_phone_nc, 0, 0);
        mSimulateTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_comp_nc, 0, 0);
        mMenuTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_setting_nc, 0, 0);
        mHomeTv.setTextColor(getResources().getColor(R.color.gray));
        mMouseTv.setTextColor(getResources().getColor(R.color.gray));
        mPowerPointTv.setTextColor(getResources().getColor(R.color.gray));
        mSimulateTv.setTextColor(getResources().getColor(R.color.gray));
        mMenuTv.setTextColor(getResources().getColor(R.color.gray));
//        播放向左或向右动画
        int checkedId = view.getId();
        final boolean _beforeCurTab;
//        判断被点击的tab是否在当前tab之前
        _beforeCurTab = mCurTabId < checkedId;

        if (_beforeCurTab)
            mTabHost.getCurrentView().startAnimation(anim_left_out);
        else
            mTabHost.getCurrentView().startAnimation(anim_right_out);
//        根据选择转换tab
        switch (checkedId) {
            case R.id.tab_home:
                mTabHost.setCurrentTabByTag(TAB_TAG_HOME);
                mHomeTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_home_c, 0, 0);
                mHomeTv.setTextColor(getResources().getColor(R.color.skyblue));
                break;
            case R.id.tab_mouse:
                mTabHost.setCurrentTabByTag(TAB_TAG_MOUSE);
                mMouseTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_mouse_c, 0, 0);
                mMouseTv.setTextColor(getResources().getColor(R.color.skyblue));
                break;
            case R.id.tab_phone:
                mTabHost.setCurrentTabByTag(TAB_TAG_PPT);
                mPowerPointTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_phone_c, 0, 0);
                mPowerPointTv.setTextColor(getResources().getColor(R.color.skyblue));
                break;
            case R.id.tab_comp:
                mTabHost.setCurrentTabByTag(TAB_TAG_SIMULATE);
                mSimulateTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_comp_c, 0, 0);
                mSimulateTv.setTextColor(getResources().getColor(R.color.skyblue));
                break;
            default:
                break;
        }
//          播放另一半动画
        if (_beforeCurTab)
            mTabHost.getCurrentView().startAnimation(anim_left_in);
        else
            mTabHost.getCurrentView().startAnimation(anim_right_in);
//        更新当前id
        mCurTabId = checkedId;
    }

    /**
     * 菜单弹出/消失处理
     */
    public void popupMenu() {
        //            保证单例
        if (popMenu == null) {
        	if(ISDEBUG) Log.i("xiaoyao", "menu created");
            //        创建菜单View实例
            View menuView = getLayoutInflater().inflate(R.layout.menu, null);
//              创建内容实例
            gridView = (GridView) menuView.findViewById(R.id.menuGridChange);
            gridView.setAdapter(new ImageAdapter(this));
//                为菜单按钮绑定跳转监听器
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    switch (i) {
                        case 0:
                            UIHelper.showSensorTest(ActivityMain.this);
                            popMenu.dismiss();
                            break;
                        case 1:
                        	UIHelper.showAbout(ActivityMain.this);
                            popMenu.dismiss();
                            break;
                        case 2:
                        	popMenu.dismiss();
                        	AppManager.getAppManager().AppExit(ActivityMain.this);
                            break;
                        case 3:
                            break;
                    }
                }
            });
//              弹出窗口实例
            popMenu = new PopMenu(this, this.mHomeTv, menuView);
        }
//          用PopWindow弹出Menu
        popMenu.show(0, this.findViewById(R.id.bar_menu).getHeight());
//            更新设置图标状态
        if(ISDEBUG) Log.i("xiaoyao", "外部状态" + popMenu.isShowing());
        if (popMenu.isShowing()) {
            mMenuTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_setting_c, 0, 0);
            mMenuTv.setTextColor(getResources().getColor(R.color.white));
        }
//        因为弹出菜单占用了焦点，所以监听消失事件来更新图标
        popMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mMenuTv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_setting_nc, 0, 0);
                mMenuTv.setTextColor(getResources().getColor(R.color.gray));
            }
        });
    }


    /**
     * 捕获tab子Activity的按键事件
     *
     * @param event 按键事件
     * @return boolean
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
//            如果硬件菜单键按下，弹出菜单
            popupMenu();
        } else if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            UIHelper.Exit(this,this.getString(R.string.surelogout));
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 弹出菜单的图像数据源
     */
    public class ImageAdapter extends BaseAdapter {

        private Context context;

        public ImageAdapter(Context context) {
            this.context = context;
        }

 
        @Override
        public int getCount() {
            return resArray.length;
        }

        @Override
        public Object getItem(int i) {
            return resArray[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LinearLayout linear = new LinearLayout(context);
            LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            linear.setOrientation(LinearLayout.VERTICAL);

            ImageView iv = new ImageView(context);
            iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
            LinearLayout.LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params2.gravity = Gravity.CENTER;
            linear.addView(iv, params2);

            TextView tv = new TextView(context);
            tv.setText(title[i]);
            LinearLayout.LayoutParams params3 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params3.gravity = Gravity.CENTER;

            linear.addView(tv, params3);

            return linear;
        }
    }
}

